<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class TopographicMapsController extends AppController {

    var $name = "TopographicMaps";

    function index($property_id) {
        $this->TopographicMap->recursive = 0;
        $this->set('property_id', $property_id);
        $cod = $this->TopographicMap->Property->field('codigo', array('Property.id' => $property_id));
        $this->Session->write('predio_codigo', $cod);
        $this->Session->write('predio_id', $property_id);
        $this->set('cod', $this->TopographicMap->Property->field('codigo', array('Property.id' => $property_id)));
        $this->set('properties', $this->TopographicMap->find('all', array('conditions' => array('TopographicMap.property_id' => $property_id), 'order' => array('TopographicMap.id DESC'), 'fields' => array('Departament.name', 'City.name', 'TopographicMap.id', 'TopographicMap.observacion', 'TopographicMap.calificacion', 'TopographicMap.vereda', 'TopographicMap.area'))));
    }

    function select() {
        Configure::write('debug', 0);
        $this->set('est', $this->Session->read('estado'));
        $this->set('cities', $this->TopographicMap->City->find('list', array(
                    'order' => 'name ASC',
                    'conditions' => array('City.departament_id' => $this->data['TopographicMap']['departament_id'])
                        )
                ));
    }

    function add($property_id) {
        $this->layout="ajax";
        $this->set('departaments', $this->TopographicMap->Departament->find('list', array('order' => array('Departament.name ASC'))));
        $this->set('property_id', $property_id);
        $this->TopographicMap->Property->recursive = -1;
        $revision = $this->TopographicMap->Property->find('first', array('conditions' => array('Property.id' => $property_id), 'fields' => array('City.name', 'City.id', 'City.departament_id', 'Property.*', 'Departament.name'), 'joins' => array(array('table' => 'cities', 'alias' => 'City', 'type' => 'LEFT', 'conditions' => array('Property.city_id=City.id')), array('table' => 'departaments', 'alias' => 'Departament', 'type' => 'left', 'conditions' => array('City.departament_id=Departament.id')))));
        $this->set('revision', $revision);
        if (!empty($this->data)) {
            if ($this->TopographicMap->saveAll($this->data)) {
                $this->Session->setFlash('Registro guardado correctamente');
                $this->redirect(array('Controller' => 'TopographicMap', 'action' => 'index', $property_id));
            } else {
                $this->Session->setFlash('No fue posible guardar los datos, por favor verifique que los campos esten correctamente diligenciados.');
            }
        }
    }

    function edit($id) {
        $this->layout="ajax";
        $this->set('departaments', $this->TopographicMap->Departament->find('list', array('order' => array('Departament.name ASC'))));
        $this->set('cities', $this->TopographicMap->City->find('list'));
        if (!empty($this->data)) {
            if ($this->TopographicMap->save($this->data)) {
                $this->Session->setFlash('Registro guardado correctamente');
                $this->redirect(array('Controller' => 'TopographicMap', 'action' => 'index', $this->data['TopographicMap']['property_id']));
            } else {
                $this->Session->setFlash('No fue posible guardar los datos, por favor verifique que los campos esten correctamente diligenciados.');
                $this->TopographicMap->recursive = -1;
                $this->data = $this->TopographicMap->find('first', array('conditions' => array('TopographicMap.id' => $id)));
                $this->TopographicMap->Property->recursive = -1;
                $revision = $this->TopographicMap->Property->find('first', array('conditions' => array('Property.id' => $this->data['TopographicMap']['property_id']), 'fields' => array('City.name', 'City.id', 'City.departament_id', 'Property.*', 'Departament.name'), 'joins' => array(array('table' => 'cities', 'alias' => 'City', 'type' => 'LEFT', 'conditions' => array('Property.city_id=City.id')), array('table' => 'departaments', 'alias' => 'Departament', 'type' => 'left', 'conditions' => array('City.departament_id=Departament.id')))));
                $this->set('revision', $revision);
            }
        } else {
            $this->TopographicMap->recursive = -1;
            $this->data = $this->TopographicMap->find('first', array('conditions' => array('TopographicMap.id' => $id)));
            $this->TopographicMap->Property->recursive = -1;
            $revision = $this->TopographicMap->Property->find('first', array('conditions' => array('Property.id' => $this->data['TopographicMap']['property_id']), 'fields' => array('City.name', 'City.id', 'City.departament_id', 'Property.*', 'Departament.name'), 'joins' => array(array('table' => 'cities', 'alias' => 'City', 'type' => 'LEFT', 'conditions' => array('Property.city_id=City.id')), array('table' => 'departaments', 'alias' => 'Departament', 'type' => 'left', 'conditions' => array('City.departament_id=Departament.id')))));
            $this->set('revision', $revision);
        }
    }

//    function delete($id, $property_id) {
//        if ($this->TopographicMap->delete($id)) {
//            $this->Session->setFlash('Registro borrado correctamente');
//            $this->redirect(array('Controller' => 'TopographicMap', 'action' => 'index', $property_id));
//        }
//    }

    public function reportAreas() {
        $this->layout = "csv";
        ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
        //create a file
        $filename = "Reporte_areas_plano_topografico_" . date("Y.m.d") . ".csv";
        $csv_file = fopen('php://output', 'w');
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');


        $sql = "SELECT City.name, Departament.name, Property.matricula, Property.codigo, Proyect.codigo, TopographicMap.area, Property.area_titulo, Property.area_negociacion FROM `topographic_maps` TopographicMap
                JOIN properties Property ON Property.id = TopographicMap.property_id
                JOIN proyects Proyect ON Proyect.id = Property.proyect_id
                JOIN cities City ON City.id = Property.city_id
                JOIN departaments Departament ON Departament.id = City.departament_id
                WHERE TopographicMap.id = ( 
                SELECT MAX( y.id ) AS id
                FROM topographic_maps y
                LEFT JOIN properties x ON x.id = y.property_id
                WHERE x.codigo = Property.codigo ) 
                GROUP BY Property.codigo
                ORDER BY TopographicMap.id ASC ";
        $results = $this->TopographicMap->query($sql);


        // The column headings of your .csv file   
        $header_row = array("CÓDIGO PROYECTO", "CÓDIGO PREDIO", "DEPARTAMENTO", "MUNICIPIO", "FOLIO MATRÍCULA", "ÁREA PLANO TOPOGRÁFICO", "ÁREA TITULO", "ÁREA NEGOCIACIÓN");

        fputcsv($csv_file, $header_row, ';', '"');

        foreach ($results as $result) {

            $row = array(
                $result['Proyect']['codigo'],
                $result['Property']['codigo'],
                $result['Departament']['name'],
                $result['City']['name'],
                $result['Property']['matricula'],
                number_format($result['TopographicMap']['area'], 4, ",", "."),
                number_format($result['Property']['area_titulo'], 4, ",", "."),
                number_format($result['Property']['area_negociacion'], 4, ",", ".")
            );

            fputcsv($csv_file, $row, ';', '"');
        }
        fclose($csv_file);
    }

}

?>
